text:
@import DSLibCore;

#pragma mark - private
@interface DSAlertsHandler ()
@property (nonatomic, strong) DSQueue *alertsQueue;
@property (nonatomic, strong) id<DSAlertView> currentAlertView;
@property (nonatomic, strong) DSAlert *currentAlert;
@property (nonatomic, assign) BOOL isOnline;
@property (nonatomic, assign) BOOL shouldShowNotReachableAlerts;
@end

@implementation DSAlertsHandler

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (id)sharedInstance
{
  DEFINE_SHARED_INSTANCE_USING_BLOCK(^
                                     {
                                       return [[DSAlertsHandler alloc] init];
                                     });
}

- (id)init
{
  self = [super init];
  if (self != nil) {
    _alertsQueue = [DSQueue queue];
    _shouldShowNotReachableAlerts = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationDidResignActive:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
  }
  return self;
}

- (void)setIsOnline:(BOOL)isOnline
{
  _isOnline = isOnline;
  if (isOnline) {
    [self setShouldShowNotReachableAlerts:YES];
  }
}

- (void)setReachability:(DSReachability *)reachability
{
  if ([self reachability]) {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
  }

  _reachability = reachability;
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(reachabilityChanged:)
                                               name:kReachabilityChangedNotification
                                             object:reachability];
}

- (void)reachabilityChanged:(NSNotification *)notification
{
  if ([(DSReachability *)[notification object] isReachable])  {
    [self setIsOnline:YES];
  }
}

#pragma mark - public
- (void)showAlert:(DSAlert *)theAlert modally:(BOOL)isModalAlert
{
  NSAssert(isModalAlert == YES, @"Only modal alert is supported now");

  void (^block)(void) = ^{
    [self queueAlert:theAlert];
  };

  if ([NSThread isMainThread]) {
    block();
  }
  else {
    dispatch_async(dispatch_get_main_queue(), block);
  }
}

- (DSAlertsQueue *)detachAlertsQueue
{
  DSAlertsQueue *queue = [[DSAlertsQueue alloc] init];
  [queue setAlertsHandler:self];
  return queue;
}

#pragma mark - alert
- (void)showModalAlert:(DSAlert *)theAlert
{
  ASSERT_MAIN_THREAD;
  id<DSAlertView> alertView = [DSAlertViewFactory modalAlertViewWithAlert:theAlert];

  [self setCurrentAlertView:alertView];
  [self setCurrentAlert:theAlert];
  DSWEAK_SELF;
  [alertView setOnDismiss:^(id<DSAlertView> _Nonnull alertView) {
    [weakSelf alertDismissed];
  }];
  [alertView show];
}

#pragma mark - queue
- (BOOL)isAlertInQueue:(DSAlert *)theAlert
{
  BOOL currentAlertEquals = [[self currentAlert] isAlertMessageEqualWith:theAlert];
  if (currentAlertEquals) {
    return YES;
  }

  BOOL alertInQueue = NO;
  for (DSAlert *queueAlert in [self alertsQueue]) {
    if ([queueAlert isAlertMessageEqualWith:theAlert]) {
      alertInQueue = YES;
      break;
    }
  }

  return alertInQueue;
}

- (BOOL)isMessage:(DSMessage *)message inCollection:(id<NSFastEnumeration>)collection {
  BOOL alertInCollection = NO;
  for (DSMessage *collectionMessage in collection) {
    if ([collectionMessage isEqualToMessage:message]) {
      alertInCollection = YES;
      break;
    }
  }

  return alertInCollection;
}

- (void)queueAlert:(DSAlert *)theAlert
{
  ASSERT_MAIN_THREAD;

  if (!theAlert) {
    return;
  }

  //If the same message is already in queue don't do anything
  if ([self isAlertInQueue:theAlert]) {
    return;
  }

  if ([self isMessage:[theAlert message]
         inCollection:[self filterOutMessages]]) {
    return;
  }
  else if ([[[theAlert message] domain] isEqualToString:NSURLErrorDomain] &&
           [[[theAlert message] code] integerValue] == NSURLErrorNotConnectedToInternet) {

    if ([self shouldShowNotReachableAlerts]) {
      [[self alertsQueue] push:theAlert];
    }

    [self setIsOnline:NO];
    NSNumber *showOfflineErrorsMoveThanOncen = [[DSAlertsHandlerConfiguration sharedInstance] showOfflineErrorsMoveThanOnce];
    if (showOfflineErrorsMoveThanOncen) {
      [self setShouldShowNotReachableAlerts:showOfflineErrorsMoveThanOncen.boolValue];
    }
    else {
#if DSAlertsHandler_SHOW_NO_INTERNET_CONNECTION_POPUPS_ONCE
      [self setShouldShowNotReachableAlerts:NO];
#endif
    }
  }
  else {
    [[self alertsQueue] push:theAlert];
  }

  [self processNextAlertFromQueue];
}

- (void)processNextAlertFromQueue
{
  ASSERT_MAIN_THREAD;

  if ([self currentAlertView] == nil) {
    DSAlert *nextAlert = [[self alertsQueue] pop];
    if (nextAlert != nil) {
      [self showModalAlert:nextAlert];//NOTE: when will add notifications(modeless alerts), fix this call
    }
  }
}

- (void)alertDismissed
{
  ASSERT_MAIN_THREAD;

  //Cleanup
  [self setCurrentAlertView:nil];
  [self setCurrentAlert:nil];

  [self processNextAlertFromQueue];
}

#pragma mark - UIAlertViewDelegate
- (void)alertViewCancel:(id<DSAlertView>)alertView
{
  [self alertDismissed];
}

//- (void)        alertView:(id<DSAlertView>)theAlertView
//didDismissWithButtonIndex:(NSInteger)theButtonIndex
//{
//  ASSERT_MAIN_THREAD;
//
//  DSAlertButton *clickedButton = nil;
//
//  if ([theAlertView isCancelButtonAtIndex:theButtonIndex]) {
//    clickedButton = [[self currentAlert] cancelButton];
//  }
//  else {
//    clickedButton = [[[self currentAlert] otherButtons]
//                     objectAtIndex:(NSUInteger)(theButtonIndex - ([[self currentAlert] cancelButton] ? 1: 0))];
//  }
//
//  [clickedButton invoke];
//  [self alertDismissed];
//}

#pragma mark - Notifications
- (void)applicationDidResignActive:(NSNotification *)notification
{
  ASSERT_MAIN_THREAD;

  [[self alertsQueue] filterWithPredicate:[NSPredicate predicateWithBlock:^BOOL(DSAlert *alert, NSDictionary *bindings) {
    return ![alert shouldDismissOnApplicationDidResignActive];
  }]];

  if ([[[self currentAlertView] alert] shouldDismissOnApplicationDidResignActive]) {
    [[self currentAlertView] dismissAnimated:NO completion:nil];
  }
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2014 - 2022 Blazebit.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>blaze-persistence-archetype</artifactId>
        <groupId>com.blazebit</groupId>
        <version>1.6.9-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>blaze-persistence-archetype-spring-boot-sample</artifactId>

    <name>Blazebit Persistence Archetype Spring-Boot Sample</name>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-resources-plugin</artifactId>
                    <configuration>
                        <escapeString>\</escapeString>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>archetype-resources/pom.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <excludes>
                    <exclude>archetype-resources/pom.xml</exclude>
                </excludes>
            </resource>
        </resources>
    </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
PyObject* c4ddev::Py4D_BaseBitmap = nullptr;
PyObject* c4ddev::Py4D_GeClipMap = nullptr;
PyObject* c4ddev::Py4D_GeUserArea = nullptr;
PyObject* c4ddev::Py4D_GeDialog = nullptr;
PyObject* c4ddev::Py4D_GeListNode = nullptr;

void c4ddev::PyTypesInit() {
  PyObject* mod = PyImport_ImportModule("c4d");
  if (mod) {
    Py4D_GeListNode = PyObject_GetAttrString(mod, "GeListNode");
  }
  mod = PyImport_ImportModule("c4d.bitmaps");
  if (mod) {
    Py4D_BaseBitmap = PyObject_GetAttrString(mod, "BaseBitmap");
    Py4D_GeClipMap = PyObject_GetAttrString(mod, "GeClipMap");
  }
  mod = PyImport_ImportModule("c4d.gui");
  if (mod) {
    Py4D_GeUserArea = PyObject_GetAttrString(mod, "GeUserArea");
    Py4D_GeDialog = PyObject_GetAttrString(mod, "GeDialog");
  }
}

PyObject* c4ddev::PyGeListNode_New(GeListNode* node, Bool owner)
{
  PythonLibrary lib;
  if (!node)
    return (PyObject*) lib.ReturnPyNone();

  PythonBase* base = lib.Alloc();
  if (!base) {
    PyErr_SetString(PyExc_MemoryError, "Couldn't allocate PythonBase");
    return nullptr;
  }

  lib.SetGeListNode(base, "node", node, owner);
  _PyObject* result = lib.GetObject(base, "node");
  if (!result) {
    PyErr_SetString(PyExc_MemoryError, "Couldn't create GeListNode reference.");
    return nullptr;
  }

  lib.IncRef(result);
  lib.Free(base);
  return (PyObject*) result;
}

GeListNode* c4ddev::PyGeListNode_Get(PyObject* obj) {
  static PythonLibrary _lib;
  GeListNode* dest = nullptr;
  if (!_lib.GetGeListNode(nullptr, reinterpret_cast<_PyObject*>(obj), dest)) {
    PyErr_SetString(PyExc_TypeError, "expected GeListNode");
    return nullptr;
  }
  return dest;
}

PyObject* c4ddev::PyString_FromString(
  String const& str, STRINGENCODING encoding)
{
  Int32 const length = str.GetCStringLen(encoding);
  AutoGeFree<Char> buffer(NewMemClear(Char, length + 1));
  if (!buffer) {
    PyErr_SetString(PyExc_MemoryError, "String::GetCStringCopy() failed");
    return nullptr;
  }
  str.GetCString(buffer, length + 1, encoding);
  return PyString_FromStringAndSize(buffer, length);
}

Bool c4ddev::PyString_AsString(PyObject* obj, String* dest) {
  if (!dest) {
    PyErr_SetString(PyExc_RuntimeError, "missing String*");
    return false;
  }
  char* str = ::PyString_AsString(obj);
  if (!str) return false;
  *dest = str;
  return true;
}

GeUserArea* c4ddev::PyGeUserArea_Get(PyObject* obj) {
  struct CPyGeUserArea : public PyObject {
      GeUserArea* _area;
      Bool _owner;
      PyObject* _weakreflist;
  };
  if (!PyObject_IsInstance(obj, Py4D_GeUserArea)) {
    PyErr_SetString(PyExc_TypeError, "expected c4d.gui.GeUserArea object");
    return nullptr;
  }
  return static_cast<CPyGeUserArea*>(obj)->_area;
}

GeClipMap* c4ddev::PyGeClipMap_Get(PyObject* obj) {
  struct CPyGeClipMap : public PyObject {
      GeClipMap* _map;
      // Possibly other members we don't know about ...
  };
  if (!PyObject_IsInstance(obj, Py4D_GeClipMap)) {
    PyErr_SetString(PyExc_TypeError, "expected c4d.bitmaps.GeClipMap object");
    return nullptr;
  }
  return static_cast<CPyGeClipMap*>(obj)->_map;
}

BaseBitmap* c4ddev::PyBaseBitmap_Get(PyObject* obj) {
  PyErr_SetString(PyExc_RuntimeError, "PyBaseBitmap_Get() does not work yet.");
  return nullptr;
  #if 0
  struct CPyBaseBitmap : public PyObject {
    // FIXME: Correct structure def?
      BaseBitmap* _bmp;
  };
  if (!PyObject_IsInstance(obj, Py4D_BaseBitmap)) {
    PyErr_SetString(PyExc_TypeError, "expected c4d.bitmaps.BaseBitmap object");
    return nullptr;
  }
  return static_cast<CPyBaseBitmap*>(obj)->_bmp;
  #endif
}

Bool c4ddev::PyBaseContainer_Get(PyObject* obj, BaseContainer* bc) {
  static PythonLibrary _lib;
  if (!bc) {
    PyErr_SetString(PyExc_RuntimeError, "missing BaseContainer*");
    return false;
  }
  if (!_lib.GetContainer(nullptr, reinterpret_cast<_PyObject*>(obj), *bc)) {
    return false;
  }
  return true;
}

PyObject* c4ddev::PyBaseContainer_New(BaseContainer const& bc) {
  PythonLibrary lib;
  PythonBase* base = lib.Alloc();
  if (!base) {
    PyErr_SetString(PyExc_MemoryError, "Couldn't allocate PythonBase");
    return nullptr;
  }

  lib.SetContainer(base, "bc", bc);
  _PyObject* result = lib.GetObject(base, "bc");
  if (!result) {
    PyErr_SetString(PyExc_MemoryError, "Couldn't create BaseContainer reference.");
    return nullptr;
  }

  lib.IncRef(result);
  lib.Free(base);
  return (PyObject*) result;
}


text:
package com.phloc.commons.tree.withid.unique;

import java.util.Collection;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.phloc.commons.parent.IChildrenProviderWithID;
import com.phloc.commons.parent.IChildrenProviderWithUniqueID;
import com.phloc.commons.state.EChange;
import com.phloc.commons.tree.withid.ITreeItemWithID;
import com.phloc.commons.tree.withid.ITreeWithID;

/**
 * A specialized version of the tree, where each item is required to have a
 * unique ID so that item searching can be performed with little runtime effort.
 *
 * @author Philip Helger
 * @param <KEYTYPE>
 *        The type of the key elements for the tree. This is typically String.
 * @param <DATATYPE>
 *        The type of the elements contained in the tree. This is the generic
 *        type to be stored in the tree.
 * @param <ITEMTYPE>
 *        The type of the tree item that will be stored in this tree.
 */
public interface ITreeWithGlobalUniqueID <KEYTYPE, DATATYPE, ITEMTYPE extends ITreeItemWithID <KEYTYPE, DATATYPE, ITEMTYPE>> extends
                                                                                ITreeWithID <KEYTYPE, DATATYPE, ITEMTYPE>,
                                                                                IChildrenProviderWithID <KEYTYPE, ITEMTYPE>,
                                                                                IChildrenProviderWithUniqueID <KEYTYPE, ITEMTYPE>
{
  /**
   * Check if a tree item corresponding to the given ID is present.
   *
   * @param aDataID
   *        The ID of the tree item to search.
   * @return true if such an item is present
   */
  boolean containsItemWithID (@Nullable KEYTYPE aDataID);

  /**
   * Get the {@link ITreeItemWithID} that corresponds to the given ID.
   *
   * @param aDataID
   *        The ID of the tree item to search.
   * @return null if no such tree item exists.
   */
  @Nullable
  ITEMTYPE getItemWithID (@Nullable KEYTYPE aDataID);

  /**
   * Get the data of the tree item that corresponds to the given ID.
   *
   * @param aDataID
   *        The ID of the tree item to search.
   * @return null if no such tree item exists.
   */
  @Nullable
  DATATYPE getItemDataWithID (@Nullable KEYTYPE aDataID);

  /**
   * @return A non-null collection of all items.
   */
  @Nonnull
  Collection <ITEMTYPE> getAllItems ();

  /**
   * @return A non-null collection of all item datas.
   */
  @Nonnull
  Collection <DATATYPE> getAllItemDatas ();

  /**
   * Remove the item with the specified ID
   *
   * @param aDataID
   *        The ID of the item to be removed
   * @return {@link EChange#CHANGED} if the item was removed,
   *         {@link EChange#UNCHANGED} otherwise. Never null.
   */
  @Nonnull
  EChange removeItemWithID (@Nullable KEYTYPE aDataID);

  /**
   * Check if one item is equal or a child of the other item. This relationship
   * is checked not only for direct children but for all levels.
   *
   * @param aParentItemID
   *        The parent item ID to a validate.
   * @param aChildItemID
   *        The item ID to check whether it is a child of the passed parent
   *        folder.
   * @return true if the child item is the same or a child of the
   *         parent item, false if one of the IDs could not be
   *         resolved or they are not in a parent-child-relationship.
   */
  boolean isItemSameOrDescendant (@Nullable KEYTYPE aParentItemID, @Nullable KEYTYPE aChildItemID);
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: talal_000
 * Date: 15.06.2015
 * Time: 16:38
 */
include 'connection.php';
$link = connection();
$countALL=0;
function support1($value)
{
    $sql = "SELECT * FROM bill_entries WHERE article_id = $value";
    $result = mysql_query($sql);
    $count = mysql_num_rows($result);
    $sql = "SELECT * FROM bill_entries";
    if ($result = mysql_query($sql))
    {
        $countAll = mysql_num_rows($result);
    }
    return round($count/$countAll,4);
}

function support2($value1, $value2)
{
    $count=0;
    $countAll=0;
    $confidence='';
    $sqlbill = "SELECT id FROM bill_entries WHERE article_id = $value1";

    if ($result = mysql_query($sqlbill)) {
        $array = array();
        // Fetch one and one row
        // get Data from shopping_cart_entries
        while ($row = mysql_fetch_assoc($result)) {
            $array[$count] = $row['id'];
            $count++;
            // posts results gotten from database(title and text) you can also show id ($results['id'])
        }
    }
    $count=0;
    $size = count($array);
    for($i=0; $i<$size; $i++)
    {
            $sql = "SELECT *  FROM bill_entries WHERE article_id = $value2 AND id = $array[$i]";

            if ($result = mysql_query($sql)) {
                $count += mysql_num_rows($result);
                //echo $count."
";
            }
    }
    $sql = "SELECT * FROM bill_entries";
    if ($result = mysql_query($sql))
    {
        $countAll = mysql_num_rows($result);
    }
    return round($count/$countAll,2);
}

function confidence($value1, $value2)
{
    return round(support2($value1, $value2)/support1($value1),4) * 100;
}

function confidenceAlle()
{
    $sqlDelete = "DELETE FROM assoziationsanalyse";
    if($result=	mysql_query($sqlDelete))
    {
        //echo 'Löschen ok!';
    }
    else echo 'Konnte nicht löschen!';

    $count=0;
    $sql = "SELECT article_id FROM bill_entries";
    $array = Array();
    if ($result = mysql_query($sql))
    {
        while ($row = mysql_fetch_assoc($result))
        {
            $value = $row['article_id'];
            if (in_array($value ,$array) == false)
            {
                $array[$count] = $value;
                $count++;
            }
        }
    }
    $size = count($array);

    for ($i=0; $i<$size; $i++)
    {
        for ($j=0; $j<$size; $j++)
        {
            if($i!=$j)
            {
               // echo 'Confidence ' . getName($array[$i]).' -> '.getName($array[$j]).' : '.confidence($array[$i],$array[$j]).' % '."
";
                $confidence = confidence($array[$i], $array[$j]);
                $sql = "INSERT INTO assoziationsanalyse(article1, article2, confidence) VALUES($array[$i], $array[$j], $confidence)
                        ON DUPLICATE KEY UPDATE article1=$array[$i], article2=$array[$j], confidence=$confidence";
                if (mysql_query($sql)) {
                    //echo "New record created successfully";
                } else {
                    echo "Error: " . $sql . "
" . mysql_error();
                }
            }
        }
    }
}

function getConfidence()
{
    $htmltable='';
    $sql = "SELECT article1, article2, confidence FROM assoziationsanalyse ORDER BY confidence DESC";
    if ($result = mysql_query($sql))
    {
        while ($row = mysql_fetch_assoc($result))
        {
            $article1 = $row['article1'];
            $articleName1 = getName($article1);
            $article2 = $row['article2'];
            $articleName2 = getName($article2);
            $confidence = $row['confidence'];
            $htmltable=$htmltable.'
'.$article1.' '.$articleName1.'	'.$article2.' '.$articleName2.'	'.$confidence.' %
';
        }
    }
    $htmlstring ='
Assoziationsanalyse

Article 1	Article 2	Confidence
'.$htmltable.'
';
    return $htmlstring;
}
?>


text:
// Module dependencies.
var xmlbuilder = require('xmlbuilder');

var Constants = require('../../../util/constants');
var HeaderConstants = Constants.HeaderConstants;
var BlobConstants = Constants.BlobConstants;

// Expose 'ContainerResult'.
exports = module.exports = ContainerResult;

function ContainerResult(name, publicAccessLevel) {
  if (name) {
    this.name = name;
  }

  if (publicAccessLevel) {
    this.publicAccessLevel = publicAccessLevel;
  }
}

ContainerResult.parse = function (containerXml) {
  var containerResult = new ContainerResult();
  for (var propertyName in containerXml) {
    switch (propertyName.toLowerCase()) {
      case 'publicaccesslevel':
        containerResult.publicAccessLevel = containerXml[propertyName];
        break;
      case 'lastmodified':
        containerResult.lastModified = containerXml[propertyName];
        break;
      default:
        containerResult[propertyName.toLowerCase()] = containerXml[propertyName];
    }
  }

  return containerResult;
};

ContainerResult.prototype.getPropertiesFromHeaders = function (headers) {
  var self = this;

  var setContainerPropertyFromHeaders = function (containerProperty, headerProperty) {
    if (!self[containerProperty] && headers[headerProperty.toLowerCase()]) {
      self[containerProperty] = headers[headerProperty.toLowerCase()];
    }
  };

  setContainerPropertyFromHeaders('etag', HeaderConstants.ETAG);
  setContainerPropertyFromHeaders('lastModified', Constants.LAST_MODIFIED_ELEMENT);

  if (!self.publicAccessLevel) {
    self.publicAccessLevel = BlobConstants.BlobContainerPublicAccessType.OFF;
    if (headers[HeaderConstants.BLOB_PUBLIC_ACCESS_HEADER]) {
      self.publicAccessLevel = headers[HeaderConstants.BLOB_PUBLIC_ACCESS_HEADER];
    }
  }

  if (self.publicAccessLevel === 'true') {
    // The container was marked for full public read access using a version prior to 2009-09-19.
    self.publicAccessLevel = BlobConstants.BlobContainerPublicAccessType.CONTAINER;
  }
};


text:
from .createmessage import CreateMessage
from .createresponse import CreateResponse


text:
/**
 * siir.es.adbWireless.adbWireless.java This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is
 * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 **/

package siir.es.adbWireless;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class Utils
{

	public static NotificationManager mNotificationManager;
	public static WakeLock mWakeLock;

	public static final int START_NOTIFICATION_ID = 1;
	public static final int ACTIVITY_SETTINGS = 2;

	public static void saveWiFiState(Context context, boolean wifiState)
	{
		SharedPreferences settings = context.getSharedPreferences("wireless", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("wifiState", wifiState);
		editor.commit();
	}

	public static void WiFidialog(final Context context)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(context.getString(R.string.no_wifi)).setCancelable(true).setPositiveButton(context.getString(R.string.button_exit), new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int id)
			{
				System.exit(0);
			}
		}).setNegativeButton(R.string.button_activate_wifi, new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int id)
			{
				Utils.enableWiFi(context, true);
				dialog.cancel();
			}
		});
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.create();
		builder.setTitle(R.string.no_wifi_title);
		builder.show();
	}

	@SuppressWarnings("deprecation")
	public static boolean adbStart(Context context)
	{
		try
		{
			if (!MainActivity.USB_DEBUG)
			{
				Utils.setProp("service.adb.tcp.port", MainActivity.PORT);
				try
				{
					if (Utils.isProcessRunning("adbd"))
					{
						Utils.runRootCommand("stop adbd");
					}
				}
				catch (Exception e)
				{}
				Utils.runRootCommand("start adbd");
			}
			try
			{
				MainActivity.mState = true;
			}
			catch (Exception e)
			{}
			SharedPreferences settings = context.getSharedPreferences("wireless", 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("mState", true);
			editor.commit();

			MainActivity.remoteViews.setImageViewResource(R.id.widgetButton, R.drawable.widgeton);
			ComponentName cn = new ComponentName(context, adbWidgetProvider.class);
			AppWidgetManager.getInstance(context).updateAppWidget(cn, MainActivity.remoteViews);

			// Try to auto connect
			if (Utils.prefsAutoCon(context))
			{
				Utils.autoConnect(context, "c");
			}

			// Wake Lock
			if (Utils.prefsScreenOn(context))
			{
				final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
				mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, context.getClass().getName());
				mWakeLock.acquire();
			}

			if (Utils.prefsNoti(context))
			{
				Utils.showNotification(context, R.drawable.ic_stat_adbwireless, context.getString(R.string.noti_text) + " " + Utils.getWifiIp(context));
			}
		}
		catch (Exception e)
		{
			return false;
		}
		return true;
	}

	public static boolean adbStop(Context context) throws Exception
	{
		try
		{
			if (!MainActivity.USB_DEBUG)
			{
				if (MainActivity.mState)
				{
					setProp("service.adb.tcp.port", "-1");
					runRootCommand("stop adbd");
					runRootCommand("start adbd");
				}
			}
			MainActivity.mState = false;

			SharedPreferences settings = context.getSharedPreferences("wireless", 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("mState", false);
			editor.commit();

			MainActivity.remoteViews.setImageViewResource(R.id.widgetButton, R.drawable.widget);
			ComponentName cn = new ComponentName(context, adbWidgetProvider.class);
			AppWidgetManager.getInstance(context).updateAppWidget(cn, MainActivity.remoteViews);

			// Try to auto disconnect
			if (Utils.prefsAutoCon(context))
			{
				Utils.autoConnect(context, "d");
			}

			// Wake Lock
			if (mWakeLock != null)
			{
				mWakeLock.release();
			}

			if (Utils.mNotificationManager != null)
			{
				Utils.mNotificationManager.cancelAll();
			}
		}
		catch (Exception e)
		{
			return false;
		}
		return true;

	}

	public static void autoConnect(Context context, String mode)
	{
		String autoConIP = Utils.prefsAutoConIP(context);
		String autoConPort = Utils.prefsAutoConPort(context);

		if (autoConIP.trim().equals("") || autoConPort.trim().equals(""))
		{
			Toast.makeText(context, R.string.autcon_incomplete, Toast.LENGTH_LONG).show();
			return;
		}

		String urlRequest = "http://" + autoConIP + ":" + autoConPort + "/" + mode + "/" + Utils.getWifiIp(context);

		try
		{
			new AutoConnectTask(urlRequest).execute();
		}
		catch (Exception e)
		{}

	}

	public static boolean isProcessRunning(String processName) throws Exception
	{
		boolean running = false;
		Process process = null;
		process = Runtime.getRuntime().exec("ps");
		BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
		String line = null;
		while ((line = in.readLine()) != null)
		{
			if (line.contains(processName))
			{
				running = true;
				break;
			}
		}
		in.close();
		process.waitFor();
		return running;
	}

	public static boolean hasRootPermission()
	{
		Process process = null;
		DataOutputStream os = null;
		boolean rooted = true;
		try
		{
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
			if (process.exitValue() != 0)
			{
				rooted = false;
			}
		}
		catch (Exception e)
		{
			rooted = false;
		}
		finally
		{
			if (os != null)
			{
				try
				{
					os.close();
					process.destroy();
				}
				catch (Exception e)
				{}
			}
		}
		return rooted;
	}

	public static boolean runRootCommand(String command)
	{
		Process process = null;
		DataOutputStream os = null;
		try
		{
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes(command + "\n");
			os.writeBytes("exit\n");
			os.flush();
			process.waitFor();
		}
		catch (Exception e)
		{
			return false;
		}
		finally
		{
			try
			{
				if (os != null)
				{
					os.close();
				}
				process.destroy();
			}
			catch (Exception e)
			{}
		}
		return true;
	}

	public static boolean setProp(String property, String value)
	{
		return runRootCommand("setprop " + property + " " + value);
	}

	public static String getWifiIp(Context context)
	{
		WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		int ip = mWifiManager.getConnectionInfo().getIpAddress();
		return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + ((ip >> 24) & 0xFF);
	}

	public static void enableWiFi(Context context, boolean enable)
	{
		if (enable)
		{
			Toast.makeText(context, R.string.turning_on_wifi, Toast.LENGTH_LONG).show();
		}
		else
		{
			Toast.makeText(context, R.string.turning_off_wifi, Toast.LENGTH_LONG).show();
		}
		WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		mWifiManager.setWifiEnabled(enable);
	}

	public static boolean checkWifiState(Context context)
	{
		try
		{
			WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
			if (!mWifiManager.isWifiEnabled() || wifiInfo.getSSID() == null)
			{
				return false;
			}

			return true;
		}
		catch (Exception e)
		{
			return false;
		}
	}

	@SuppressWarnings("deprecation")
	public static void showNotification(Context context, int icon, String text)
	{
		final Notification notifyDetails = new Notification(icon, text, System.currentTimeMillis());
		notifyDetails.flags = Notification.FLAG_ONGOING_EVENT;
		if (prefsSound(context))
		{
			notifyDetails.defaults |= Notification.DEFAULT_SOUND;
		}
		if (prefsVibrate(context))
		{
			notifyDetails.defaults |= Notification.DEFAULT_VIBRATE;
		}
		Intent notifyIntent = new Intent(context, MainActivity.class);
		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0, notifyIntent, 0);
		notifyDetails.setLatestEventInfo(context, context.getResources().getString(R.string.noti_title), text, intent);

		if(Utils.mNotificationManager == null)
		{
			Utils.mNotificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
		}
			Utils.mNotificationManager.notify(Utils.START_NOTIFICATION_ID, notifyDetails);
	}

	public static boolean prefsOnBoot(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_onboot_key), false);
	}

	public static boolean prefsVibrate(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_vibrate_key), true);
	}

	public static boolean prefsSound(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_sound_key), true);
	}

	public static boolean prefsNoti(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_noti_key), true);
	}

	public static boolean prefsHaptic(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_haptic_key), true);
	}

	public static boolean prefsWiFiOn(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_wifi_on_key), false);
	}

	public static boolean prefsWiFiOff(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_wifi_off_key), false);

	}

	public static boolean prefsAutoCon(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_autocon_key), false);
	}

	public static String prefsAutoConIP(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getString(context.getResources().getString(R.string.pref_autoconip_key), "");
	}

	public static String prefsAutoConPort(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getString(context.getResources().getString(R.string.pref_autoconport_key), "8555");
	}

	public static boolean prefsScreenOn(Context context)
	{
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		return pref.getBoolean(context.getResources().getString(R.string.pref_screenon_key), false);
	}

}


text:
SQLDelight generates typesafe kotlin APIs from your SQL statements. It verifies your schema, statements, and migrations at compile-time and provides IDE features like autocomplete and refactoring which make writing and maintaining SQL simple.

SQLDelight understands your existing SQL schema.

```sql
CREATE TABLE hockey_player (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  number INTEGER NOT NULL
);
```

It generates typesafe code for any labeled SQL statements.

![intro.gif](images/intro.gif)

---

SQLDelight supports a variety of dialects and platforms:

SQLite

* [Android](android_sqlite)
* [Native (iOS, macOS, or Windows)](native_sqlite)
* [JVM](jvm_sqlite)
* [Javascript](js_sqlite)
* [Multiplatform](multiplatform_sqlite)

[MySQL (JVM)](jvm_mysql)

[PostgreSQL (JVM)](jvm_postgresql) (Experimental)

[HSQL/H2 (JVM)](jvm_h2) (Experimental)

## Snapshots

Snapshots of the development version (including the IDE plugin zip) are available in
[Sonatype's `snapshots` repository](https://oss.sonatype.org/content/repositories/snapshots/com/squareup/sqldelight/). Note that all coordinates are app.cash.sqldelight instead of com.squareup.sqldelight for 2.0.0+ SNAPSHOTs.
=== "Kotlin"
    ```kotlin
    // settings.gradle.kts
    pluginManagement {
        repositories {
            gradlePluginPortal()
            maven(url = "https://oss.sonatype.org/content/repositories/snapshots")
        }
    }

    // build.gradle.kts
    plugins {
        id("app.cash.sqldelight") version "SNAPSHOT-VERSION"
    }

    repositories {
        maven(url = "https://oss.sonatype.org/content/repositories/snapshots")
    }
    ```
=== "Groovy"
    ```groovy
    // settings.gradle
    pluginManagement {
        repositories {
            gradlePluginPortal()
            maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
        }
    }

    // build.gradle
    plugins {
        id "app.cash.sqldelight" version "SNAPSHOT-VERSION"
    }

    repositories {
        maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
    }
    ```

[Alpha IDE plugins are also available](https://plugins.jetbrains.com/plugin/8191-sqldelight/versions/alpha) by using the alpha channel in IntelliJ: `https://plugins.jetbrains.com/plugins/alpha/com.squareup.sqldelight`.
Snapshots are also available in the [EAP](https://plugins.jetbrains.com/plugin/8191-sqldelight/versions/eap) channel: `https://plugins.jetbrains.com/plugins/eap/com.squareup.sqldelight`

<img width="738" alt="IntelliJ_alpha_channel" src="https://user-images.githubusercontent.com/22521688/168236653-e32deb26-167f-46ce-9277-ea169cbb22d6.png">


text:
import NotificationsConstants from './NotificationsConstants';

export default NotificationsActions = Object.freeze({

	tokenReceived(dispatch, token) {
		console.log('token from FCM', token);
		dispatch({
			type: NotificationsConstants.TOKEN_RECEIVED,
			token
		});
	}

});


text:
from setuptools import setup, find_packages

setup(name="sqlalchemy_gevent",
	version = '0.2',
	url="https://github.com/hkwi/sqlalchemy_gevent",
	author="Hiroaki KAWAI",
	author_email="hiroaki.kawai@gmail.com",
	py_modules=["sqlalchemy_gevent",],
	install_requires = ["sqlalchemy", "gevent>=1.0"],
	test_suite = "tests",
	entry_points = '''
[sqlalchemy.dialects]
gevent_drizzle=sqlalchemy_gevent:DrizzleDialect
gevent_drizzle.mysqldb=sqlalchemy_gevent:DrizzleMysqldbDialect
gevent_firebird=sqlalchemy_gevent:FirebirdDialect
gevent_firebird.fdb=sqlalchemy_gevent:FirebirdFdbDialect
gevent_firebird.kinterbasdb=sqlalchemy_gevent:FirebirdKinterbasdbDialect
gevent_mssql.adodbapi=sqlalchemy_gevent:MssqlAdodbapiDialect
gevent_mssql=sqlalchemy_gevent:MssqlDialect
gevent_mssql.mxodbc=sqlalchemy_gevent:MssqlMxodbcDialect
gevent_mssql.pymssql=sqlalchemy_gevent:MssqlPymssqlDialect
gevent_mssql.pyodbc=sqlalchemy_gevent:MssqlPyodbcDialect
gevent_mssql.zxjdbc=sqlalchemy_gevent:MssqlZxjdbcDialect
gevent_mysql.cymysql=sqlalchemy_gevent:MysqlCymysqlDialect
gevent_mysql=sqlalchemy_gevent:MysqlDialect
gevent_mysql.gaerdbms=sqlalchemy_gevent:MysqlGaerdbmsDialect
gevent_mysql.mysqlconnector=sqlalchemy_gevent:MysqlMysqlconnectorDialect
gevent_mysql.mysqldb=sqlalchemy_gevent:MysqlMysqldbDialect
gevent_mysql.oursql=sqlalchemy_gevent:MysqlOursqlDialect
gevent_mysql.pymysql=sqlalchemy_gevent:MysqlPymysqlDialect
gevent_mysql.pyodbc=sqlalchemy_gevent:MysqlPyodbcDialect
gevent_mysql.zxjdbc=sqlalchemy_gevent:MysqlZxjdbcDialect
gevent_oracle.cx_oracle=sqlalchemy_gevent:OracleCx_oracleDialect
gevent_oracle=sqlalchemy_gevent:OracleDialect
gevent_oracle.zxjdbc=sqlalchemy_gevent:OracleZxjdbcDialect
gevent_postgresql=sqlalchemy_gevent:PostgresqlDialect
gevent_postgresql.pg8000=sqlalchemy_gevent:PostgresqlPg8000Dialect
gevent_postgresql.psycopg2=sqlalchemy_gevent:PostgresqlPsycopg2Dialect
gevent_postgresql.pypostgresql=sqlalchemy_gevent:PostgresqlPypostgresqlDialect
gevent_postgresql.zxjdbc=sqlalchemy_gevent:PostgresqlZxjdbcDialect
gevent_sqlite=sqlalchemy_gevent:SqliteDialect
gevent_sqlite.pysqlite=sqlalchemy_gevent:SqlitePysqliteDialect
gevent_sybase=sqlalchemy_gevent:SybaseDialect
gevent_sybase.pyodbc=sqlalchemy_gevent:SybasePyodbcDialect
gevent_sybase.pysybase=sqlalchemy_gevent:SybasePysybaseDialect
'''
)


text:
#ifndef __cuda__single_sm_matrix_vector_multiply_h__
#define __cuda__single_sm_matrix_vector_multiply_h__

#if 0
/** Given a matrix[ni][no] with stride stride, multiply by the vector[ni] and
    overwrite the vector[no] with the output.  The size of the vector should
    be at least max(no, ni).  Splits the work over the given number of
    threads.  Works best if the vector is in shared memory; global memory will
    be slow.

    It always goes through the matrix in such a way that the unit stride is
    respected.
*/
__device__ void
matrix_vector_multiply_left(const float * matrix,
                            const float * vector,
                            int ni, int no, int stride,
                            int num_threads_on_multiprocessor)
{
    /* We want to have each thread working here, even if no is much less
       than the number of threads.  To do so, we assign each thread to
       a certain o value and a certain subset of the i values, and then
       accumulate the updates, broadcasting them at the end.

       For example:
       32 threads
       2 outputs

       So we have 16 threads working on each example

       100 threads
       16 outputs

       So we have 7 threads on the first 4 examples, and 6 threads on
       the rest.

       32 threads
       100 outputs

       So most threads do 3 examples but the first 4 do 4.
*/

    int nt = num_threads_on_multiprocessor;

    for (unsigned o_start = 0;  o_start < no;  o_start += nt) {

        int nob = std::min(nt, no - o_start);  // no for the block

        int min_threads = nt / no;  // min num threads for the block
        int left_over   = nt % no;  // left over to help with extra work
        int max_threads = min_threads + (left_over > 0);

        int o = tid % no;    // which o value are we working on?
        int idx = tid / no;  // which thread in that block?
        int o_threads = min_threads + (o < left_over);

        double accum = 0.0;

        for (unsigned i = idx;  i < ni;  i += o_threads) {
            // warning: bank conflicts...
            float inval = vector[i];
            float weight = matrix[i * w_stride + o];

            accum += weight * inval;
        }

        if (max_threads > 1) {

            __syncthreads();

            if (tid < no) vector[tid] = biases[l][tid];

            __syncthreads();

            /* Now we accumulate them, allowing each thread to increment in its
               turn. */
            for (unsigned i = 0;  i < max_threads;  ++i, __syncthreads())
                if (i == idx) vector[o] += accum;
        }
    }
    else {
        /* More outputs than threads.  We break up into blocks. */

        __syncthreads();

        if (__any(tid < no)) {

            if (tid < no)
                this_layer_outputs[tid]
                    = vector[tid]
                    = transform(vector[tid], activation);
        }
    }
    else {
        accum += biases[l][o];
        this_layer_outputs[o]
            = vector[o]
            = transform(accum, activation);

    }
}

#endif

#endif /* __cuda__single_sm_matrix_vector_multiply_h__ */


text:
using NPoco;

namespace $safeprojectname$.Data
{

    public class DataServiceInterceptors : IDataInterceptor
    {

        public bool OnInserting(IDatabase database, InsertContext insertContext)
        {
            var poco = insertContext.Poco; // cast if necessary

            if (poco != null)
            {
                // ...
            }

            return true;
        }

        public bool OnUpdating(IDatabase database, UpdateContext updateContext)
        {
            var poco = updateContext.Poco; // cast if necessary

            if (poco != null)
            {
                // ...
            }

            return true;

        }

        public bool OnDeleting(IDatabase database, DeleteContext deleteContext)
        {
            var context = deleteContext;
            return true;

        }

    }

}


text:
<?php
namespace TeamTNT\TNTSearch\Support;

class Tokenizer extends AbstractTokenizer implements TokenizerInterface
{
    static protected $pattern = '/[^\p{L}\p{N}\p{Pc}\p{Pd}@]+/u';

    public function tokenize($text, $stopwords = [])
    {
        $text  = mb_strtolower($text);
        $split = preg_split($this->getPattern(), $text, -1, PREG_SPLIT_NO_EMPTY);
        return array_diff($split, $stopwords);
    }
}


text:
import { Context, HttpCall, HttpResponse } from "../../../src";

export const ExampleApi = "example";

export interface ExampleApi {
    hello(): string;
    onGet(ctx: Context, call: HttpCall): Promise<HttpResponse>;
    onPost(ctx: Context, call: HttpCall): Promise<HttpResponse>;
    other(ctx: Context, call: HttpCall): Promise<HttpResponse>;
}


text:
jQuery(document).ready(function($){
	$('.color-picker').iris();
});